<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>
    <script>
        function setValue(id, value) {
            const element = document.getElementById(id)
            if (element.tagName === 'P')
                element.innerText = value
            else
                element.value = value
        }

        function setError(msg) {
            setValue('error', msg)
        }

        function setResult(result) {
            setValue('result', result)
        }

        function f(url, token, body) {
            const method = body ? 'POST' : 'GET'
            const headers = { 'Content-type': 'application/json' }
            if (token) {
                headers['authorization'] = 'Bearer ' + token
            }
            return fetch(url, { method, headers, body }).then(res => {
                const result = res.json()
                if (res.status !== 200) {
                    result.then(response => setError(response.message))
                }
                return result
            }).catch(({message}) => setError(message))
        }

        function login() {
            const username = document.getElementById('username').value
            const password = document.getElementById('password').value
            if (!username || !password) {
                setError('must input username and password')
                return
            }
            const body = JSON.stringify({ username, password })
            f('http://localhost:9000/api/authenticate', '', body).then(res => {
                if(!res || !res.token) return
                setValue('token', res.token)
                setResult(JSON.stringify(res))
                setError('')
            })
        }

        function getCompany() {
            const token = document.getElementById('token').value
            if (!token) {
                setError('cannot fetch company without token')
                return
            }
            f('http://localhost:9000/api/company/1', token).then(res => {
                setResult(JSON.stringify(res))
                setError('')
            })
        }
    </script>
</head>
<body>
<div style="padding: 1rem; width: 900px">
    <p style="color: darkred" id="error"></p>
    Username: <input id="username" value="admin"/> <br/>
    Password: <input id="password" type="password" value="12345678"/> <br/>
    <button type="button" onclick="login()">Login</button>
    <hr/>
    Token: <br/>
    <textarea cols="120" rows="10" id="token"></textarea>
    <hr/>
    <button type="button" onclick="getCompany()">Get company</button>
    <p id="result"></p>

</div>

</body>
</html>